import React from 'react'
import { Redirect } from "react-router-dom";
import { GetUserLocal } from "./common/UserStore.js";

export default function requireLogin(BaseComponent) {
  // 创建验证组件
  return class requireLogin extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        login: false
      }
    }

    componentWillMount() {
      this.checkAuth();
    }

    componentWillReceiveProps(nextProps) {
      this.checkAuth();
    }

    checkAuth() {
      // 判断登陆
      const login = GetUserLocal();

      if (!login ) {
        //没有登录，重定向到登录界面
        this.setState({ login: false })
      } else {
        // 已经登录渲染对应组件
        this.setState({ login: true })
      }
    }

    render() {
      if (this.state.login) {
        return <BaseComponent {...this.props} />
      } else {
        return <Redirect to='/login' />
      }
    }
  }
}